package com.start.security.handler;

import com.alibaba.fastjson2.JSONObject;
import com.start.common.api.Result;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户身份验证失败
 */
@Component
public class UserUnauthorizedHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
//        httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value(), HttpStatus.UNAUTHORIZED.getReasonPhrase());
        httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());

        httpServletResponse.getWriter().write(JSONObject.toJSONString(Result.fail401("用户未登录")));
    }

}
